package com.ff.neuropp.service;

import com.ff.neuropp.domain.Work;
import com.ff.neuropp.repository.WorkRepository;
import com.ff.neuropp.util.SpecificationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class WorkService {

    @Autowired
    private WorkRepository workRepository;

    /**
     * 创建实体
     *
     * @param work
     */
    public Work saveWork(Work work) {
        return workRepository.save(work);
    }

    /**
     * 根据id查找实体
     *
     * @param id
     * @return
     */
    public Work findById(Integer id) {
        Optional<Work> optional = workRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    /**
     * 根据id 删除实体
     * @param id
     */
    public void deleteById(Integer id) {
        workRepository.deleteById(id);
    }

    /**
     * 分页条件查询
     *
     * @param work
     * @return
     */
    public Page<Work> findPage(Work work) {
        Map<String, Object> sqlParams = new HashMap<>();
        if (null == work.getPageNo()) {
            work.setPageNo(1);
        } else if (work.getPageNo() < 1) {
            work.setPageNo(1);
        }
        if (null == work.getPageSize()) {
            work.setPageSize(10);
        }
        sqlParams.put("GT_id",0);
        if(null !=work.getWorkName() && work.getWorkName().trim().length()>0){
            sqlParams.put("LIKE_workName",work.getWorkName());
        }

        if(null !=work.getStatus()){
            sqlParams.put("EQ_status",work.getStatus());
        }

        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "id";
        Pageable pageable = new PageRequest(work.getPageNo()-1,work.getPageSize(), direction, sort);
        return workRepository.findAll(SpecificationUtil.buildSpecification(sqlParams, Work.class), pageable);
    }

    /**
     * 根据条件查询List
     */
    public List<Work> findList(Map<String, Object> param) {
        return workRepository.findAll(SpecificationUtil.buildSpecification(param, Work.class));
    }
}
